package com.example.IO;

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static java.nio.channels.FileChannel.MapMode.READ_WRITE;

/**
 * @Title: MMap1
 * @Description: TODO
 * @Date 2022/1/10 14:23
 */
public class MMap1 {


    private final static String CONTENT = "我要测试零拷贝写入数据";
    private final static String FILE_NAME = "/Users/yangyue/Downloads/1.txt";

    public static void main(String[] args) {
        Path path = Paths.get(FILE_NAME);
        byte[] bytes = CONTENT.getBytes(Charset.forName("UTF-8"));
        //实现Closeable或AutoCloseable接口，并重写close方法
        try (FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ,
                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
            MappedByteBuffer mappedByteBuffer = fileChannel.map(READ_WRITE, 0, bytes.length);
            if (mappedByteBuffer != null) {
                mappedByteBuffer.put(bytes);
                mappedByteBuffer.force();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
